<template>
  <div style="width:100%;display: flex;flex-direction: column;height: 100%;border-radius: 5px;padding:15px"
       class="list-page tableMeta">
    <div style="width: 100%;position: relative;">
      <Tabs :datas="tabs" v-model="currentTab" style="padding-bottom: 5px"></Tabs>
      <div style="display: inline-block;position: absolute;right: 10px;top:5px">
        <!--        <Button color="primary">从数据源导入</Button>-->
        <!--        <Button color="primary">从数据集导入</Button>-->
        <Button color="primary" icon="jeicon-import" @click="importFields">导入字段</Button>
        <Button color="primary" icon="jeicon-general-table" @click="genTable">生成数据表</Button>
        <Button :loading="loading" color="primary" icon="jeicon-save" @click="onSubmit">保存</Button>
        <Button icon="jeicon-take-back" @click="back">返回</Button>
      </div>
    </div>
    <div style="flex: 1;height: 100%;overflow:hidden;">
      <div style="height: 100%;overflow-y: auto;padding-top: 10px">
        <div v-show="currentTab=='params'" style="height: 100%;">
          <FiledGroup style="height: 100%;">
            <Form :model="data" :rules="rules" mode="twocolumn" ref="form">
              <Legend title="连接设置">
                <FormItem label="数据源" prop="dataSource" required>
                  <Select v-model="data.dataSource" :datas="dataSources" placeholder="数据源"
                          :deletable="false"></Select>
                </FormItem>
                <FormItem label="表名" prop="tableName" required>
                  <Input type="text" v-model="data.tableName"/>
                </FormItem>
              </Legend>
              <Legend title="显示设置">
                <FormItem label="标题" prop="title" required>
                  <Input type="text" v-model="data.title"/>
                </FormItem>
              </Legend>

              <Legend title="权限设置">
                <FormItem label="列表权限" prop="authList">
                  <Input type="text" v-model="data.authList"/>
                </FormItem>
                <FormItem label="创建权限" prop="authCreate">
                  <Input type="text" v-model="data.authCreate"/>
                </FormItem>
                <FormItem label="删除权限" prop="authDelete">
                  <Input type="text" v-model="data.authDelete"/>
                </FormItem>
                <FormItem label="修改权限" prop="authModify">
                  <Input type="text" v-model="data.authModify"/>
                </FormItem>
                <FormItem label="列表角色" prop="roleList">
                  <Input type="text" v-model="data.roleList"/>
                </FormItem>
                <FormItem label="创建角色" prop="roleCreate">
                  <Input type="text" v-model="data.roleCreate"/>
                </FormItem>
                <FormItem label="删除角色" prop="roleDelete">
                  <Input type="text" v-model="data.roleDelete"/>
                </FormItem>
                <FormItem label="修改角色" prop="roleModify">
                  <Input type="text" v-model="data.roleModify"/>
                </FormItem>
              </Legend>
              <Legend title="接口设置">
                <FormItem label="查询语句" prop="loadSql">
                  <Input type="text" v-model="data.loadSql"/>
                </FormItem>
                <FormItem label="查询全部" prop="loadAllSql">
                  <Input type="text" v-model="data.loadAllSql"/>
                </FormItem>
                <FormItem label="列表接口" prop="listApi">
                  <Input type="text" v-model="data.listApi"/>
                </FormItem>
                <FormItem label="详情接口" prop="detailApi">
                  <Input type="text" v-model="data.detailApi"/>
                </FormItem>
                <FormItem label="保存接口" prop="saveApi">
                  <Input type="text" v-model="data.saveApi"/>
                </FormItem>
                <FormItem label="删除接口" prop="deleteApi">
                  <Input type="text" v-model="data.deleteApi"/>
                </FormItem>
                <FormItem label="页面地址" prop="pageUrl">
                  <Input type="text" v-model="data.pageUrl"/>
                </FormItem>
                <FormItem label="目录" prop="dirName">
                  <Input type="text" v-model="data.dirName"/>
                </FormItem>
              </Legend>
              <Legend title="其它设置">
                <FormItem label="表说明" prop="memo" single>
                  <Textarea v-model="data.memo"/>
                </FormItem>
              </Legend>
            </Form>
          </FiledGroup>
        </div>
        <div v-if="currentTab=='field'" class="list" style="margin-top: 0 !important;height: 100%;overflow-y: hidden;position: relative;">
          <div style="height: 100%;overflow-y: hidden;overflow-x: auto">
            <div class="h-table" style="width:100%">
              <table class="h-table-header h-table-header-table" style="width:100%">
                <tr>
                  <th class="text-center w60">序号</th>
                  <th class="text-center w120">字段名</th>
                  <th class="text-center w120">标题</th>
                  <th class="text-center w120">字段类型</th>
                  <th class="text-center w60">长度</th>
                  <th class="text-center w60">小数</th>
                  <th class="text-center w60">主键</th>
                  <th class="text-center w60">非空</th>
                  <th class="text-center w60">列表</th>
                  <th class="text-center w60">表单</th>
                  <th class="text-center w60">查询</th>
                  <th class="text-center w120">
                    <LinkButtons>
                      <Button icon="h-icon-plus" @click="addField()">新字段</Button>
                    </LinkButtons>
                  </th>
                </tr>
              </table>
              <div class="h-table-container" style="overflow: auto;width: 100%">
                <Draggable :list="data.fieldsMeta" handle=".mover" animation="500" tag="table"
                           class="h-table-body-table field-table" style="width: 100%;">
                  <transition-group>
                    <tr v-for="(it,index) in data.fieldsMeta" :key="it.id" style="background-color: white"
                        :class="{'h-table-tr-selected':currentField.id==it.id}"
                    >
                      <td class="text-left w60 mover" style="cursor: move;">{{ index + 1 }}</td>
                      <td class="text-center w120">
                        <Input type="text" v-model="it.columnName" class="w115"/>
                      </td>
                      <td class="text-center w120">
                        <Input type="text" v-model="it.title" class="w115"/>
                      </td>
                      <td class="text-center w120">
                        <Select :datas="columnTypes" v-model="it.nativeType" :deletable="false" class="w115"/>
                      </td>
                      <td class="text-center w60">
                        <NumberInput type="text" v-model="it.length" class="w55"/>
                      </td>
                      <td class="text-center w60">
                        <NumberInput type="text" v-model="it.scale" class="w55"/>
                      </td>
                      <td class="text-center w60">
                        <Checkbox v-model="it.primaryKey"></Checkbox>
                      </td>
                      <td class="text-center w60">
                        <Checkbox v-model="it.mandatory"></Checkbox>
                      </td>
                      <td class="text-center w60">
                        <Checkbox v-model="it.visibleInList"></Checkbox>
                      </td>
                      <td class="text-center w60">
                        <Checkbox v-model="it.visibleInForm"></Checkbox>
                      </td>
                      <td class="text-center w60">
                        <Checkbox v-model="it.searchCondition"></Checkbox>
                      </td>
                      <td class="text-center w120">
                        <LinkButtons>
                          <Button @click="delField(it)">删除</Button>
                        </LinkButtons>
                      </td>
                    </tr>
                  </transition-group>
                </Draggable>
              </div>
            </div>

          </div>
        </div>
        <DataTableListView v-if="currentTab=='list'" :data="data"/>
        <DataTableForm v-if="currentTab=='form'" :data="data"/>
      </div>
    </div>
    <div class="bar" v-if="false">
      <Form :model="currentField" mode="threecolumn">
        <FormItem label="字段名">
          <Input type="text" v-model="currentField.columnName"/>
        </FormItem>
        <FormItem label="主键策略" v-if="currentField.primaryKey">
          <Select v-model="currentField.strategy" :datas="strategys"/>
        </FormItem>
        <FormItem label="显示分组" v-if="currentField.visibleInForm">
          <Select v-model="currentField.viewGroup" keyName="k" titleName="k" :datas="data.viewGroups"/>
        </FormItem>
        <FormItem label="校验规则" v-if="currentField.visibleInForm">
          <Select :datas="verifies" v-model="data.verify"></Select>
        </FormItem>
        <FormItem label="控件类型" v-if="currentField.visibleInForm||currentField.searchCondition">
          <Select :datas="controls" v-model="currentField.controlType"></Select>
        </FormItem>
        <FormItem label="搜索类型" v-if="currentField.searchCondition">
          <Select :datas="searchTypes" v-model="currentField.searchType"></Select>
        </FormItem>
        <FormItem label="列表项" v-if="isSourceControl(currentField.controlType)">
          <Select :datas="controls" v-model="currentField.options"></Select>
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script setup>
import {ajax, uuid} from 'framework'
import {ref, reactive, nextTick} from 'vue'
import {message, confirm} from 'heyui'
import IconSelect from "../platform/IconSelect.vue";
import {VueDraggableNext as Draggable} from 'vuedraggable'
import DataTableListView from "./dataTableListView.vue";
import {useRouter} from 'vue-router'
import DataTableForm from "./dataTableForm.vue";

const router = useRouter()

const currentTab = ref('params')
const tabs = [
  {key: 'params', title: '参数配置'},
  {key: 'field', title: '字段配置'},
  // {key: 'index', title: '索引配置'},
  {key: 'list', title: '列表配置'},
  {key: 'form', title: '表单配置'}
]
const verifies = {
  IDCardNo: '身份证',
  CnMobile: '手机号',
  Email: '邮箱',
  tel: '电话号码',
  url: '网址'
}

const controls = [
  {key: 'Text', title: '文本框'},
  {key: 'Select', title: '下拉框'},
  {key: 'Checkbox', title: '多选框'},
  {key: 'Radio', title: '单选框'},
  {key: 'TextArea', title: '文本区'},
  {key: 'Date', title: '日期选择'},
  {key: 'Time', title: '时间选择'},
  {key: 'DateTime', title: '日期-时间选择'},
  {key: 'Switch', title: '开关'},
  {key: 'SwitchList', title: '选项切换'},
  {key: 'File', title: '文件上传'},
  {key: 'Image', title: '图片'},
  {key: 'Number', title: '数字'},
  {key: 'Map', title: '地图选点'}
]
const isSourceControl = (it) => ['Select', 'Checkbox', 'Radio', 'SwitchList'].indexOf(it) > -1
const dbTypes = [
  {key: 'MySQL', title: 'MySQL'},
  {key: 'H2', title: 'H2'}
]
const strategys = [
  {key: "ASSIGN", title: "手动复制"},
  {key: "SEQUENCE", title: "最大号表"},
  {key: "IDENTITY", title: "自增"},
  {key: "GENERATOR", title: "UUID"}
]
const columnTypes = ["varchar", "int", "decimal", 'date', 'timestamp']
const searchTypes = ["相等", "包含", "左边一样", "右边一样", "大于", "大于等于", "小于", "小于等于", "中间", "不等"]
//事件
//Props Open方法传入的参数
const {params} = defineProps({
  params: Object,
})
const currentField = ref({})

//dialog.cancel() 方法可以直接关闭对话框
//打开Dialog时进行初始化
let isAdd = false
if (params.value.id) {
  //通知Dialog处于loading状态
  //dialog.loading(true)
  ajax.get("tableMeta/detail", params.value).then(r => {
    Object.assign(data, r.data)
        // dialog.loading(false)
  })
} else {
  isAdd = true
}

//属性和状态
let form = ref(null)

//表单数据
const data = reactive({
  id: null,
  title: null,
  dataSource: 'default',
  tableName: null,
  fieldsMeta: [],
  idStrategy: null,
  loadSql: null,
  loadAllSql: null,
  indexModels: null,
  dirName: null,
  dirPath: null,
  memo: null,
  viewGroups: [],
  formModel: 'onecolumn',
  authList: null,
  authCreate: null,
  authDelete: null,
  authModify: null,
  roleList: null,
  roleCreate: null,
  roleDelete: null,
  roleModify: null,
  listApi: null,
  detailApi: null,
  saveApi: null,
  deleteApi: null,
  pageUrl: null,
  enable: null,
  crateTime: null,
  createUser: null,
})
//验证规则
const rules = {}
const dataSources = ref([])
ajax.post('tableMeta/dataSources').then(r => {
  dataSources.value = r.data
})
const back=()=>{
  router.go(-1)
}

const loading=ref(false)
/**
 * 提交数据
 */
const onSubmit=() => {
  let validResult = form.value.valid();
  if (validResult.result) {
    loading.value=true
    ajax.post(isAdd ? 'tableMeta/add' : 'tableMeta/save', data).then(r => {
      message("已保存")
      if (isAdd && r.data) {
        data.id = r.data
        isAdd = false
      }
     // dialog.emit('dataupdate')

      // dialog.success(r.data)
    }).catch(e => {
      message.error(e.message)
    }).finally(f => loading.value=false)
  } else {
    currentTab.value = 'params'
    nextTick(() => {
      form.value.valid()
    })
  }
}



function addField(f = {}) {
  let fl = data.fieldsMeta.length
  let newField = Object.assign({
    id: uuid(),
    columnName: 'field_' + fl,
    title: '字段' + fl,
    controlType: 'Text',
    nativeType: 'varchar',
    length: '100',
    scale: 0,
  }, f)

  data.fieldsMeta.push(newField)
  currentField.value = newField
}

function delField(v) {
  let i = data.fieldsMeta.indexOf(v)
  if (i > -1) {
    if (currentField.value == v) {
      currentField.value = {}
    }
    data.fieldsMeta.splice(i, 1)
  }
}

function fieldSelect(v) {
  currentField.value = v
}

function genTable() {
  ajax.post("tableMeta/checkTable?id=" + data.id)
      .then(r => new Promise(resolve => {
        if (!r.data) {
          resolve()
        } else {
          confirm({
            content: '数据库中已存在表，是否重新生成表？', onConfirm() {
              resolve()
            }
          })
        }
      }))
      .then(r => {
        ajax.post("tableMeta/genTable?id=" + data.id)
      })
}

function importFields() {
  if (!data.dataSource) {
    message("先请选择数据源");
    return
  }
  if (!data.tableName) {
    message("请填写表名");
    return
  }
  confirm({
    content: "是否从数据库表中导入字段？",
    onConfirm: async () => {
      let r = await ajax.post("tableMeta/importFieldsFromTable?dataSource=" + data.dataSource + "&tableName=" + data.tableName)
      //console.log(r)
      for (let d of r.data) {
        addField(d)
      }
    },
  })

}
</script>
<style lang="less">
.table-btn-bar {
  position: absolute;
  right: 10px;
  top: 8px;
  z-index: 6;
}

.tableMeta {
  .h-numberinput-show .h-numberinput-input {
    min-width: 20px
  }

  .w120 {
    width: 120px;
  }

  .w115 {
    width: 115px;
  }

  .w60 {
    width: 60px;
  }

  .w55 {
    width: 55px;
  }

  .field-table input.h-input, .field-table .h-numberinput-show {
    background: transparent;
    border-color: transparent;
  }

  .field-table input.h-input:focus, .field-table .h-numberinput-show:focus {
    border-color: var(--pc);
  }

  .field-table input.h-input:hover, .field-table .h-numberinput-show:hover {
    border-color: var(--pc-bt-hover);
  }

  .h-select-show {
    background-color: transparent;
  }
}
</style>
